const Busboy = require('busboy');
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')

module.exports = async (ctx, next) => {
  if(ctx.path === '/upload' && ctx.method === 'POST'){
    if(!ctx.is('multipart/form-data')) {
      ctx.throw(415)
    }
    const busboy = new Busboy({ headers: ctx.req.headers });
    let originName = ''
    let saveName = ''
    let savePath = ''
    busboy.on('file', async (fieldname, file, filename, encoding, mimetype) => {
      originName = filename
      saveName = crypto.randomBytes(Math.ceil(24 / 2)).toString('hex').slice(0, 24) + path.extname(filename);
      savePath = 'storage/' + require('../utils/date.js').datestr()
      await fs.promises.mkdir(savePath, { recursive: true })
      const writable = fs.createWriteStream(path.join(savePath,saveName));
      file.pipe(writable) 
    });
    await new Promise((resolve, reject) => {
      ctx.req.pipe(busboy);
      ctx.req.on('error', err => {
        reject(err)
      })
      ctx.req.on('end', () => {
        resolve()
      })
    })
    ctx.body = {
      filename: originName,
      filepath: savePath,
      filesize: '',
      fileext: '',
      uploader_id: '',
      is_cover: false,
      water: false,
      url: ctx.protocol + '://' + ctx.host + path.join(savePath,saveName).substr(7),
      hash: '',
      module: ''
    }
  } else {
    next()
  }
}